import type { ReactNode } from 'react';
import React, { useCallback } from 'react';
import { Header, Grid } from 'gantd';
import { isEmpty } from 'lodash';
import { commonText } from '@/utils/utils';
import SearchForm from '@/components/searchform';

interface SelectorPanelProps {
  searchFormTitle?: string | ReactNode;
  onCancel?: () => void;
  onOk?: (selectedRowKeys: string[], selectedRows: object[]) => void;
  [propName: string]: any;
}

const View = (props: SelectorPanelProps) => {
  const {
    viewKey,
    searchFormTitle = tr('查询'),
    initParams,
    schema,
    uiSchema,
    customComponents,
    onSearch,
    onSizeChange,
    autoSearch,

    showHeader,
    gridHeaderProps,

    columns,
    tableHeight,
    selectedRowKeys,
    selectedRows,
    dataSource,
    multiple,
    valueProp,
    loading,
    onSelect,
    rowSelection: customRowSelection,
    extraSearchProps,
    ...restProps
  } = props;

  const handlerSelect = useCallback((selectedRowKeys, selectedRows) => {
    onSelect && onSelect(selectedRowKeys, selectedRows);
  }, []);

  return (
    <div>
      {!isEmpty(schema) && (
        <SearchForm
          searchKey={`loupeSelectSearchForm:${viewKey}`}
          title={searchFormTitle}
          headerProps={{ type: 'line' }}
          initParams={initParams}
          onSearch={onSearch}
          uiSchema={uiSchema}
          schema={schema}
          customComponents={customComponents}
          onSizeChange={onSizeChange}
          autoSearch={autoSearch}
          {...extraSearchProps}
        />
      )}
      {showHeader && <Header title={commonText.smartGridTitleText} type="line" {...gridHeaderProps} />}
      <Grid
        hideMenuItemExport
        columns={columns}
        rowkey={valueProp}
        dataSource={dataSource}
        loading={loading}
        height={tableHeight}
        rowBuffer={50}
        rowSelection={{
          type: multiple ? 'multiple' : 'single',
          selectedKeys: selectedRowKeys,
          selectedRows,
          onSelect: handlerSelect,
          ...customRowSelection,
        }}
        {...restProps}
      />
    </div>
  );
};

View.defaultProps = {
  multiple: false,
  schema: {},
  uiSchema: {},
  autoSearch: false,

  columns: [],
  dataSource: [],
  valueProp: 'id',
  labelProp: 'name',
  tableHeight: 'auto',
  extraSearchProps: {},
};
export default View;
